<?php

namespace app\admin\controller;

use app\common\model\DawnbyteMatchLivesModel;
use app\common\model\MatchLivesModel;
use app\common\NStatus;
use think\facade\Request;

class MatchlivesController extends BaseController
{
    public function index()
    {
        return view("index", [
            "sports" => NStatus::Sports,
            "all_status" => NStatus::AllStatus,
        ]);
    }

    public function index2()
    {
        return $this->assign([
            "stutus" => json_encode(DawnbyteMatchLivesModel::AllStatus, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
        ])->fetch();
    }

    public function lists()
    {
        $all = Request::param();
        $page = Request::param("page");
        $limit = Request::param("limit");
        $where = [];
        $match_status = 0;
        $sport_id = 0;
        if (isset($all["start_time"]) && $all["start_time"] > 0 && isset($all["end_time"]) && $all["end_time"] > 0) {
            $where[] = ["match_time", ">=", strtotime($all["start_time"])];
            $where[] = ["match_time", "<=", strtotime($all["end_time"])];
        }
        if (isset($all["home"]) && $all["home"]) {
            $where[] = ["home", "LIKE", $all["home"] . "%"];
        }
        if (isset($all["away"]) && $all["away"]) {
            $where[] = ["away", "LIKE", $all["away"] . "%"];
        }
        if (isset($all["match_id"]) && $all["match_id"]) {
            $where[] = ["match_id", "=", $all["match_id"]];
        }
        if (isset($all["sport_id"]) && $all["sport_id"]) {
            $sport_id = $all["sport_id"];
            $where[] = ["sport_id", "=", $all["sport_id"]];
        }
        if (isset($all["category"]) && $all["category"]) {
            $where[] = ["category", "=", $all["category"]];
        }

        //match_status 1未开始 2 进行中 3 完场
        if (isset($all["match_status"]) && is_numeric($all["match_status"])) {
            $match_status =  $all["match_status"];
            if ($match_status == 1){
                $where[] = ["standard_match_status", "=", 2];
            }else if ($match_status == 2){
                $where[] = ["standard_match_status", "=", 1];
            }else if ($match_status == 3){
                $where[] = ["standard_match_status", "=", 3];
            }
        }
        $lists = [];
        $count  = MatchLivesModel::where($where)->order("match_time", "desc")->count();
        if($count > 0){
            $lists = MatchLivesModel::where($where)->order("match_time", "desc")->limit(($page - 1) * $limit, $limit)->select()->toArray();
        }
        
        if (Request::get("export") == 1) {
            if ($count > 0) {
                // 记录日志
                parent::addAdminLog('导出赛事连接报表');
                $this->export($lists);
                exit();
            }
            self::bulidFail("未查询到相关数据");
        }


        if (count($lists) > 0) {
            return json([
                "code" => 0,
                "msg" => "",
                "data" => $lists,
                "count" => $count
            ]);
        }
        return self::bulidFail("未查询到相关数据");
    }

    public function lists2()
    {
        $page = $this->get("page", 1);
        $limit = $this->get("limit", 20);
        if (($match_id = $this->get('match_id')) && is_numeric($match_id)) {
            if ($model = DawnbyteMatchLivesModel::where('match_id', $match_id)->find()) {
                return json([
                    "code" => 0,
                    "msg" => "",
                    "data" => [$model->toArray()],
                    "count" => 1
                ]);
            }
            return json([
                "code" => 1,
                "msg" => '<font color="red">赛事ID不存在</font>',
                "data" => [],
                "count" => 0
            ]);
        } else {
            $model = DawnbyteMatchLivesModel::field('*');

            if (in_array($category = trim($this->get('category', '')), ['101', '102'])) {
                $model = $model->where('category_id', $category);
            }

            if ($home = trim($this->get('home', ''))) {
                $model = $model->where('home', $home);
            }

            if ($away = trim($this->get('away', ''))) {
                $model = $model->where('away', $away);
            }

            if (in_array($match_status = $this->get('match_status', 0), ['1', '2', '3'])) {
                if ($category == '101') {
                    switch ($match_status) {
                        case '1':
                            $model = $model->where('match_status', 1);
                            break;
                        case '2':
                            $model = $model->whereIn('match_status', [2, 3, 4, 5, 6]);
                            break;
                        case '3':
                            $model = $model->where('match_status', 7);
                            break;
                    }
                } elseif ($category == '102') {
                    switch ($match_status) {
                        case '1':
                            $model = $model->where('match_status', 1);
                            break;
                        case '2':
                            $model = $model->whereIn('match_status', [2, 3, 4, 5, 6, 7, 8, 9]);
                            break;
                        case '3':
                            $model = $model->where('match_status', 10);
                            break;
                    }
                }
            }

            $start_time = strtotime(trim($this->get('start_time', '')));
            $end_time = strtotime(trim($this->get('end_time', '')));

            if ($start_time && $end_time) {
                $model = $model->whereBetween('match_start_time', [$start_time, $end_time]);
            } elseif ($start_time) {
                $model = $model->whereBetween('match_start_time', [$start_time, time()]);
            }

            if ($this->get("export") == '1') {
                $list = [];
                $model->chunk(100, function ($querys) use (&$list) {
                    foreach ($querys as $query) {
                        $list[] = [
                            $query->match_id,
                            $query->category_id == 101 ? '足球' : '篮球',
                            $query->name_zh_full,
                            $query->home,
                            $query->away,
                            date('Y-m-d H:i:s', $query->match_start_time),
                            $query->hd,
                            $query->uhd,
                        ];
                    }
                }, 'match_start_time', 'desc');

                // 记录日志
                parent::addAdminLog('导出破晓赛事报表');

                return export_excel(
                    $list,
                    ['比赛ID', '比赛类型', '所属赛事', '主队', '客队', '比赛开始时间', '标清直播地址', '高清直播地址'],
                    '破晓赛事',
                    '破晓赛事'
                );
            }

            return json([
                "code" => 0,
                "msg" => "",
                "data" => $model->order('match_id', 'desc')
                    ->page($page, $limit)
                    ->select()
                    ->toArray(),
                "count" => DawnbyteMatchLivesModel::count('match_id')
            ]);
        }
    }

    private function export($data)
    {
        $title = [
            '比赛ID', '比赛时间', '比赛状态', '比赛类型', '所属赛事',
            '主队', '客队',
            '超清直播地址', '高清直播地址', '标清直播地址',
        ];
        foreach ($data as &$datum) {
            // $datum["sport_id"]   = NStatus::Sports[$datum["sport_id"]] ?? "未知";
            $datum["match_time"] = date("Y-m-d H:i:s", $datum["match_time"]);
            unset($datum['category'], $datum['sport_id']);
        }
        export_excel($data, $title, "比赛连接-" . date("YmdHis"), "比赛列表数据");
    }

    public function auto_live()
    {
        $id = Request::param("id");
        if (intval($id) <= 0) {
            return self::bulidFail("数据异常");
        }

        $set = MatchLivesModel::where("match_id", $id)->find();

        $auto_live = $set['auto_live'] > 0 ? 0 : 1;

        $query = MatchLivesModel::where("match_id", $id)->update(['auto_live' => $auto_live]);

        if (!$query) {
            return self::bulidFail();
        }

        return self::bulidSuccess();
    }
}
